package cn.xiehang.SoundSight;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class ShareFragment extends Fragment {

    File imageFile;
    File audioFile;
    ImageView imageView;
    CheckBox checkBox;
    EditText editTitle;
    EditText editContent;
    Button btnShareSubmit;
    String sharePageURL=SeverURL.URL+"/share_page";

    public ShareFragment(File imageFile, File audioFile) {
        this.imageFile = imageFile;
        this.audioFile = audioFile;
    }

    @Override
    public View onCreateView(@Nullable LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 加载布局文件
        View view = inflater.inflate(R.layout.fragment_share, container, false);

        // 初始化控件
        initViews(view);
        //邦定事件
        initData();

        //设置图片
        initializationImageView(imageFile);
        return view;
    }
    @Override
    public void onResume() {
        super.onResume();
        //设置图片
        initializationImageView(imageFile);
    }

    private void initializationImageView(File imageFile) {
        if (imageFile != null) {
            imageView.setImageURI(android.net.Uri.fromFile(imageFile));
        } else {
            imageView.setImageResource(R.drawable.ic_launcher_background);
        }
    }

    private void initData() {
        btnShareSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取SharedPreferences实例
                SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);

                //如果没有获取到用户名和密码，则提示用户登录
                if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                    builder.setTitle("提示")
                            .setMessage("请先登录")
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 关闭对话框
                                dialog.dismiss();
                            })
                            .show();
                    return;
                }
// 获取用户ID
                String username = sharedPref.getString("username", null);
                String password = sharedPref.getString("password", null);

                // 1. 创建 OkHttpClient
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(30, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .build();

                RequestBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("audio", audioFile.getName(), RequestBody.create(MediaType.parse("audio/mpeg"), audioFile))
                        .addFormDataPart("username",username)
                        .addFormDataPart("password",password)
                        .addFormDataPart("title", editTitle.getText().toString())
                        .addFormDataPart("content", editContent.getText().toString())
                        .addFormDataPart("image", imageFile.getName(), RequestBody.create(MediaType.parse("image/jpeg"), imageFile))
                        .addFormDataPart("have_audio", String.valueOf(checkBox.isChecked()))
                        .build();

                // 3. 构建请求
                Request request = new Request.Builder()
                        .url(sharePageURL)
                        .post(requestBody)
                        .build();
                // 4. 发送请求
                client.newCall(request).enqueue(new okhttp3.Callback() {
                    @Override
                    public void onFailure(okhttp3.Call call, IOException e) {
                        // 处理请求失败
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                        if (response.isSuccessful()) {
                            try {
                                String responseData = response.body().string();
                                JSONObject json = new JSONObject(responseData);
                                // 处理返回的JSON数据
                                String message= json.has("message")? json.getString("message") : "上传成功";
                                requireActivity().runOnUiThread(() -> {
                                    Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
                                    //清除文本框
                                    editTitle.setText("");
                                    editContent.setText("");
                                    checkBox.setChecked(false);
                                    // 上传成功后，跳转到社区页面
                                    FragmentActivity activity = getActivity();
                                    if (activity != null) {
                                        // 执行 Fragment 切换
                                        FragmentManager fm=activity.getSupportFragmentManager();
                                        FragmentTransaction transaction = fm.beginTransaction();
                                        //隐藏所有的Fragment
                                        for (Fragment frag : fm.getFragments()) {
                                            if (frag != null && frag.isAdded()) {
                                                transaction.hide(frag);
                                            }
                                        }
                                        Fragment existingFragment = fm.findFragmentByTag("ThirdFragment");

                                        if (existingFragment != null) {
                                            //从存储信息中更新
                                            ((ThirdFragment) existingFragment).getArticles();

                                            transaction.show(existingFragment);
                                        } else {
                                            // 创建新的 ShareFragment 实例
                                            Fragment fragment = ThirdFragment.newInstance();
                                            // 添加到 FragmentManager
                                            transaction.add(R.id.FragmentContainer, fragment, "ThirdFragment");
                                        }
                                        transaction.commit();
                                }
                            });
                            }
                            catch (Exception e) {
                                requireActivity().runOnUiThread(() -> {
                                    Toast.makeText(getContext(), "解析数据失败"+e.getMessage(), Toast.LENGTH_SHORT).show();
                                });
                            }
                        } else {
                            // 处理请求失败
                            System.out.println("Request failed: " + response.message());
                        }
                    }
                });

            }
        });

    }

    private void initViews(View view) {
        imageView = view.findViewById(R.id.share_fragment_image);
        checkBox = view.findViewById(R.id.share_audio_checkbox);
        editTitle = view.findViewById(R.id.share_fragment_title_edit_text);
        editContent = view.findViewById(R.id.share_fragment_context_text);
        btnShareSubmit = view.findViewById(R.id.btnShareSubmit);



    }
    public void setImageFile(File imageFile) {
        this.imageFile = imageFile;
    }
    public void setAudioFile(File audioFile) {
        this.audioFile = audioFile;
    }
}
